use axum::{Router, Json};
use axum::extract::Query;
use axum::routing::get;
use serde::{Serialize, Deserialize};

use crate::models::{Comment, Guide};
// use tower_cookies::Cookies;

// use crate::models::User;
// use crate::utils::cookie;

type RouterResult<T> = Result<T,String>;


// struct RouterResponse {

// }

#[derive(Serialize,Deserialize)]
struct DataResponse<T>{
    pub status: &'static str,
    pub data: Vec<T>,
}

impl<T> DataResponse<T> {
    pub fn new(status:&'static str,data: Vec<T>) -> DataResponse<T> {
        DataResponse{
            status: status,
            data: data
        }
    }
}

pub fn router() -> Router {
    Router::new()
        .route("/", get(index))
        .route("/get_all", get(get_all_guide))
        .route("/get_comments",get(get_comments_by_guide_id))
        .route("/forbid",get(forbid_guide))
        .route("/prime",get(prime_guide))
        .route("/active",get(active_guide))
}

async fn index() -> RouterResult<String> {
    Ok("欢迎来到论坛页面！".to_string())
}


#[derive(Deserialize,Serialize,Debug)]
struct ChangeGuideStatus{
    guide_id:i32
}

async fn forbid_guide(Query(query):Query<ChangeGuideStatus>) -> Json<bool> {
    if let Ok(_) = Guide::forbid_guide_by_id(query.guide_id).await{
        return Json(true)
    }
    Json(false)
}
async fn prime_guide(Query(query):Query<ChangeGuideStatus>) -> Json<bool> {
    if let Ok(_) = Guide::prime_guide_by_id(query.guide_id).await{
        return Json(true)
    }
    Json(false)
}
async fn active_guide(Query(query):Query<ChangeGuideStatus>) -> Json<bool> {
    if let Ok(_) = Guide::active_guide_by_id(query.guide_id).await{
        return Json(true)
    }
    Json(false)
}

async fn get_all_guide() -> Json<Vec<Guide>> {
    let guides = Guide::fetch_all().await.unwrap();

    // let rs = DataResponse::new("ok",guides);


    Json(guides)

}
#[derive(Serialize,Deserialize,Debug)]
struct GetComment{
    pub guide_id:i32
}
/// 通过guide_id获取它对应的所有comment
async fn get_comments_by_guide_id(Query(query):Query<GetComment>) -> Json<Vec<Comment>> {

    let result = Guide::fetch_comments_of(query.guide_id).await;

    if let Ok(comments) = result{
        Json(comments)
    }else{
        // println!("Error:{}",result.err().unwrap())
        if let Err(e) = result {
            println!("Error! {:?}",e);
        }
        Json(vec![])
    }


}